import {
  app,
  BrowserWindow,
  globalShortcut,
  ipcMain,
  Menu,
  nativeImage,
  shell,
  Tray
} from 'electron'
import { join } from 'path'
import './hardwareInfo'
import { electronApp, is, optimizer } from '@electron-toolkit/utils'
import request from '../renderer/src/request'
import { setMsgMainWindow } from './messageBus'
import RouterConstant from '../renderer/src/components/constant/routerConstant'

let homeWindow = null

function createWindow(route) {
  const isHome = route && RouterConstant.Home === route
  if (isHome && homeWindow) {
    homeWindow.show()
    return
  }
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 1300,
    height: 850,
    minHeight: 850,
    icon: nativeImage.createFromPath('resources/icon/icon.png'),
    minWidth: 1300,
    show: false,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  mainWindow.setMenu(null)

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  // 监听窗口关闭事件，阻止默认行为并隐藏窗口
  mainWindow.on('close', (event) => {
    event.preventDefault()
    mainWindow.hide()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'] + '/#' + route)
  } else {
    // 修改: 在加载页面时拼接 route 参数
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'), {
      hash: route
    })
    // 注册 F12 手动开启调试
    globalShortcut.register('F12', () => {
      mainWindow.webContents.openDevTools()
    })
  }

  // 注册 F5 快捷键刷新页面
  globalShortcut.register('F5', () => {
    if (!mainWindow.isDestroyed()) {
      mainWindow.webContents.reload() // 刷新当前页面
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  if (isHome) {
    const icon = nativeImage.createFromPath('resources/icon/icon.png')
    // 创建托盘图标
    const tray = new Tray(icon)
    const contextMenu = Menu.buildFromTemplate([
      { label: '首页', click: () => createWindow(RouterConstant.Home) },
      {
        label: '退出',
        click: () => {
          globalShortcut.unregisterAll() // 注销所有全局快捷键
          mainWindow.destroy() // 关闭主窗口
          app.quit() // 退出程序
        }
      }
    ])
    tray.setContextMenu(contextMenu)
    tray.on('click', () => {
      if (mainWindow.isVisible()) {
        mainWindow.hide()
      } else {
        mainWindow.show()
      }
    })
    homeWindow = mainWindow
  }

  //把websocket的窗口存储起来
  if (route && RouterConstant.WebSocketTool === route) {
    setMsgMainWindow(mainWindow)
  }
}

ipcMain.handle('createWindow', async (event, route) => {
  createWindow(route)
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))

  createWindow(RouterConstant.Home)

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

ipcMain.handle('axios-request', async (event, config) => {
  return request.request(config)
})
